'use strict';

angular.module('afasApp')
  .controller('TermsCtrl', ['$scope', 'Services', '$state', '_', '$filter', function ($scope, Services, $state, _, $filter) {

    // SET VARIABLE
    $scope.terms       = [];
    $scope.coursetypes = [];
    $scope.termNew     = {};
    $scope.selectedCourseTypes = [];
    $scope.psForm      = false;
    $scope.totalItems  = 0;
    $scope.termNew     = {
      'StartDate': new Date(),
      'EndDate'  : new Date()
    };
    $scope.params = {
      'pagesize': 10,
      'order_by': 'Year',
      'order_type': 'DESC'
    };
    $scope.errors = {};

    // COURSE TYPES
    Services.getItems($scope.COURSETYPE_URL)
    .then(function(results){
      $scope.coursetypes = results.data;
      $scope.params.course_type = $scope.coursetypes[0].Id;
    });

    // PAGINATION
    $scope.pagesize = 10;

    $scope.pagination = {
      current: 1
    };

    $scope.pageChanged = function(newPage) {
      getResultsPage(newPage);
    };

    function getResultsPage(pageNumber) {
      $scope.params.page = (pageNumber - 1);
      $scope.pagination.current = pageNumber;
      Services.getItems('terms', $scope.params)
      .then(function( results ) {
        var pagingData = angular.fromJson(results.headers['x-pagination']);
        $scope.totalItems = pagingData.TotalCount;
        $scope.terms = results.data;
      });
    }
    getResultsPage(1);

    $scope.loadTerms = function(Id) {
      $scope.params.course_type = Id;
      getResultsPage($scope.pagination.current);
    };

    $scope.orderBy = function(field) {
      if ($scope.params.order_by === field) {
        if ($scope.params.order_ype === 'ASC') {
          $scope.params.order_ype = 'DESC';
        } else {
          $scope.params.order_ype = 'ASC';
        }
      } else {
        $scope.params.order_ype = 'ASC';
      }
      $scope.params.order_by = field;
      getResultsPage($scope.pagination.current);
    };

    $scope.validate = function(courseType) {
      var items = _.where($scope.selectedCourseTypes, {Id: courseType.Id});
      var item = _.findWhere($scope.selectedCourseTypes, {Id: courseType.Id});

      if (items.length > 0) {
        $scope.selectedCourseTypes = _.without($scope.selectedCourseTypes, item);
      } else {
        $scope.selectedCourseTypes.push(courseType);
      }
    };

    // CONTROLLER FUNCTION
    $scope.addTerm = function () {
      // Terms.addTerm($scope.termNew);
      $scope.termNew.StartDate = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
      $scope.termNew.EndDate = $filter('date')($scope.timepicker.timeB, 'yyyy-MM-dd');
      $scope.errors = {};
      var term = [];
      angular.forEach($scope.selectedCourseTypes, function(value, key){
        var objectTerm = {
          'StartDate': $scope.termNew.StartDate,
          'EndDate'  : $scope.termNew.EndDate,
          'Number'   : $scope.termNew.Number,
          'Year'     : $scope.termNew.Year,
          'CourseType': {
            'Id': value.Id
          }
        };
        term.push(objectTerm);
      });
      Services.add('terms', term)
      .then(function(results){
        $scope.psForm = false;
        $scope.termNew = {};
        $scope.selectedCourseTypes = [];
        getResultsPage($scope.pagination.current);
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteTerm = function (term) {
      Services.delete('terms', term)
      .then(function(results){
        console.log(results);
        getResultsPage($scope.pagination.current);
      });
    };
  }])
  .controller('TermCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.currentTerm = {};
    $scope.currentID   = $stateParams.id;
    $scope.currentTerm = {};

    Services.getItem('terms', $scope.currentID)
    .then(function(results){
      $scope.currentTerm = results.data;

      $scope.currentTerm.StartDate = $filter('date')($scope.currentTerm.StartDate, 'yyyy-MM-dd HH:mm:ss');
      $scope.currentTerm.EndDate = $filter('date')($scope.currentTerm.EndDate, 'yyyy-MM-dd HH:mm:ss');
      // $scope.currentTerm.StartDate = new Date($scope.currentTerm.StartDate);
      // $scope.currentTerm.EndDate   = new Date($scope.currentTerm.EndDate);
    });

    $scope.updateTerm = function () {
      Services.update('terms', $scope.currentTerm, $scope.currentID)
      .then(function(results){
        console.log(results);
        $state.go( '^.show', {id: $scope.currentID} );
      });
    };
  }])
  .controller('TermTargetCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.termTargets = {};
    $scope.courseTypes = [];

    $scope.params = {
      'course_types': '',
      'year': ''
    }

    Services.getItems('course_types')
    .then(function(results){
      $scope.courseTypes = results.data;
    })

    $scope.loadTarget = function(){
      if ($scope.params.course_types === '') {
        $scope.params.course_types = '1,2,3,4';
      };
      Services.getItems('registration_figures', $scope.params)
      .then(function(results){
        $scope.termTargets = results.data;
      });
    };

    $scope.editThis = function(term){
      term.Editing = true;
    };

    $scope.submitThis = function(term){
      Services.update('terms', term, term.Id)
      .then(function(results){
        term.Editing = false;
      });
    };

    $scope.cancelThis = function(term){
      term.Editing = false;
    }
  }]);